package com.fish.common.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpCacheFilter implements Filter {
	private long cacheTime;
	private String []filterUrl;
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
			throws IOException, ServletException {
		filterchain.doFilter(servletrequest, servletresponse);
		if (servletrequest instanceof HttpServletRequest && servletresponse instanceof HttpServletResponse) {
			HttpServletRequest request = (HttpServletRequest) servletrequest;
			HttpServletResponse response = (HttpServletResponse) servletresponse;
			String uir=request.getRequestURI();
			if(this.filterUrl!=null&&this.filterUrl.length>0){
				for(String url:this.filterUrl){
					if(uir.indexOf(url)!=-1){
						//log.info("requestURI:" + request.getRequestURI()+", has seted max-age");
						response.setHeader("Cache-Control", "max-age=" + cacheTime);
						break;
					}
				}
			}
		}
	}

	@Override
	public void init(FilterConfig filter) throws ServletException {
		String cacheTime=filter.getInitParameter("cacheTime");
		String filterUrl=filter.getInitParameter("filterUrl");
		this.cacheTime=Long.valueOf(cacheTime)*60*60*1000;
		this.filterUrl=filterUrl.split(",");
		
	}
}
